import React, { useState, useCallback, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import back from "../../assets/icon/common_icon_back_black_n.png";
import close from "../../assets/icon/message_icon_close_n.png";
import noSearchImg from "../../assets/hdpi/no_search_message.png";
import "./index.css";
import { useDebounce } from "../../components/Debounce";
import { searchService, handleApiResponse, handleApiError } from "../../utils/api";
import type { 
  DoctorSearchItem, 
  DrugSearchItem, 
  DiseaseSearchItem,
  SearchHistoryItem 
} from "../../type";

const SearchPage: React.FC = React.memo(() => {
  const navigate = useNavigate();
  const [searchValue, setSearchValue] = useState<string>("");
  const [doctorList, setDoctorList] = useState<DoctorSearchItem[]>([]);
  const [drugList, setDrugList] = useState<DrugSearchItem[]>([]);
  const [diseaseList, setDiseaseList] = useState<DiseaseSearchItem[]>([]);
  const [searchFlag, setSearchFlag] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string>("");

  // 搜索历史管理
  const [searchHistory, setSearchHistory] = useState<SearchHistoryItem[]>(() => {
    const history = localStorage.getItem('searchHistory');
    return history ? JSON.parse(history) : [];
  });

  // 保存搜索历史
  const saveSearchHistory = useCallback((keyword: string, type: 'doctor' | 'drug' | 'disease' = 'doctor') => {
    if (!keyword.trim()) return;
    
    const newHistoryItem: SearchHistoryItem = {
      id: Date.now().toString(),
      keyword: keyword.trim(),
      type,
      timestamp: Date.now()
    };

    const updatedHistory = [
      newHistoryItem,
      ...searchHistory.filter(item => item.keyword !== keyword.trim())
    ].slice(0, 10); // 只保留最近10条

    setSearchHistory(updatedHistory);
    localStorage.setItem('searchHistory', JSON.stringify(updatedHistory));
  }, [searchHistory]);

  // 删除搜索历史
  const removeSearchHistory = useCallback((id: string) => {
    const updatedHistory = searchHistory.filter(item => item.id !== id);
    setSearchHistory(updatedHistory);
    localStorage.setItem('searchHistory', JSON.stringify(updatedHistory));
  }, [searchHistory]);

  // 搜索请求
  const searchRequest = useCallback(async (keyword: string) => {
    if (!keyword.trim()) {
      setSearchFlag(false);
      return;
    }

    setLoading(true);
    setError("");
    setSearchFlag(true);

    try {
      const response = await searchService.getHomePageSearch({ keyWord: keyword });
      const result = handleApiResponse<{
        doctorSearchVoList: DoctorSearchItem[];
        drugsSearchVoList: DrugSearchItem[];
        diseaseSearchVoList: DiseaseSearchItem[];
      }>(response);

      setDoctorList(result.doctorSearchVoList || []);
      setDrugList(result.drugsSearchVoList || []);
      setDiseaseList(result.diseaseSearchVoList || []);
    } catch (err) {
      const errorMessage = handleApiError(err);
      setError(errorMessage);
      console.error('搜索失败:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  // 防抖搜索
  const delayedQuery = useDebounce(searchRequest, 500);

  // 输入处理
  const handleInput = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setSearchValue(value);
    delayedQuery(value);
  }, [delayedQuery]);

  // 搜索按钮点击
  const handleSearch = useCallback(() => {
    if (searchValue.trim()) {
      searchRequest(searchValue);
      saveSearchHistory(searchValue);
    }
  }, [searchValue, searchRequest, saveSearchHistory]);

  // 历史记录点击
  const handleHistoryClick = useCallback((keyword: string) => {
    setSearchValue(keyword);
    searchRequest(keyword);
  }, [searchRequest]);

  // 热门搜索点击
  const handleHotSearchClick = useCallback((keyword: string) => {
    setSearchValue(keyword);
    searchRequest(keyword);
    saveSearchHistory(keyword);
  }, [searchRequest, saveSearchHistory]);
  // 热门搜索数据
  const hotSearchList = useMemo(() => [
    "阿胶", "小可爱医生", "感冒", "头疼", "神经病", "发烧", 
    "癫痫", "阿莫西林", "脱发", "肾虚", "腿抽筋", "感冒灵颗粒", "哈人哈", "哈哈"
  ], []);

  // 搜索结果组件
  const SearchResultList = React.memo(() => (
    <div className="search_list">
      {doctorList.length > 0 && (
        <div className="search_box_content_doctor">
          <div className="content_List_doctor">医生</div>
          <ul className="content_List_doctor_ul">
            {doctorList.map((doctor) => (
              <li key={doctor.doctorId} onClick={() => saveSearchHistory(doctor.doctorName, 'doctor')}>
                {doctor.doctorName}
              </li>
            ))}
          </ul>
        </div>
      )}
      
      {drugList.length > 0 && (
        <div className="search_box_content_drug">
          <div className="content_List_drug">药品</div>
          <ul className="content_List_drug_ul">
            {drugList.map((drug) => (
              <li key={drug.drugsId} onClick={() => saveSearchHistory(drug.drugsName, 'drug')}>
                {drug.drugsName}
              </li>
            ))}
          </ul>
        </div>
      )}
      
      {diseaseList.length > 0 && (
        <div className="search_box_content_disease">
          <div className="content_List_disease">病症</div>
          <ul className="content_List_disease_ul">
            {diseaseList.map((disease) => (
              <li key={disease.diseaseId} onClick={() => saveSearchHistory(disease.diseaseName, 'disease')}>
                {disease.diseaseName}
              </li>
            ))}
          </ul>
        </div>
      )}
      
      {!loading && doctorList.length === 0 && drugList.length === 0 && diseaseList.length === 0 && searchValue && (
        <div className="no-search-result">
          <img src={noSearchImg} alt="无搜索结果" />
          <p>暂无搜索结果</p>
        </div>
      )}
    </div>
  ));

  // 搜索历史组件
  const SearchHistory = React.memo(() => (
    <div className="search_box_content_history">
      <div className="content_history_title">搜索历史</div>
      <ul className="content_history_ul">
        {searchHistory.map((item) => (
          <li key={item.id}>
            <span onClick={() => handleHistoryClick(item.keyword)}>
              {item.keyword}
            </span>
            <img 
              src={close} 
              alt="删除" 
              onClick={() => removeSearchHistory(item.id)}
            />
          </li>
        ))}
      </ul>
    </div>
  ));

  // 热门搜索组件
  const HotSearch = React.memo(() => (
    <div className="search_box_content_hot">
      <div className="content_hot_title">热门搜索</div>
      <ul className="content_hot_ul">
        {hotSearchList.map((keyword, index) => (
          <li key={index} onClick={() => handleHotSearchClick(keyword)}>
            {keyword}
          </li>
        ))}
      </ul>
    </div>
  ));

  return (
    <div className="search_box">
      <div className="search_box_top">
        <img
          className="search_box_back"
          src={back}
          alt="返回"
          onClick={() => navigate(-1)}
        />
        <input
          className="input"
          type="text"
          placeholder="病症、药品名称、医生姓名"
          value={searchValue}
          onChange={handleInput}
        />
        <button className="search_btn" onClick={handleSearch}>
          {loading ? "搜索中..." : "搜索"}
        </button>
      </div>
      
      {error && (
        <div className="error-message">
          {error}
        </div>
      )}
      
      <div className="search_box_content">
        {searchFlag ? (
          <SearchResultList />
        ) : (
          <div className="search_content">
            <SearchHistory />
            <HotSearch />
          </div>
        )}
      </div>
    </div>
  );
});

SearchPage.displayName = 'SearchPage';

export default SearchPage;

